<?php
/**
 * User: Julien
 * Date: 23/08/13
 * Time: 6:45
 */

use PHPImageWorkshop\ImageWorkshop;

class Application_Service_UploadImage
{
    /**
     * @var array
     */
    private $configParams;

    public function __construct(array $configInputParams = null)
    {
        $options = Zend_Registry::get('Zend_Application_Options');
        $this->configParams = $options['image_workshop'];

        if ($configInputParams) {
            if (isset($configInputParams['thumbnailWidth'])) $this->configParams['thumbnailWidth'] = $configInputParams['thumbnailWidth'];
            if (isset($configInputParams['thumbnailHeight'])) $this->configParams['thumbnailHeight'] = $configInputParams['thumbnailHeight'];
            if (isset($configInputParams['pictureWidth'])) $this->configParams['pictureWidth'] = $configInputParams['pictureWidth'];
            if (isset($configInputParams['pictureHeight'])) $this->configParams['pictureHeight'] = $configInputParams['pictureHeight'];
            if (isset($configInputParams['imageQuality'])) $this->configParams['imageQuality'] = $configInputParams['imageQuality'];
        }
    }

    /**
     * @param string $tmpName The path coming from $_FILES['image']['tmp_name']
     * @param int $imageId
     * @param string $imageType This can be 'store' or 'discount'
     */
    public function uploadAndResizeImages($tmpName, $imageId, $imageType)
    {
        $layer = ImageWorkshop::initFromPath($tmpName);
        $this->_uploadAndResizeImage($layer, $imageId, $imageType, 'picture');
        $this->_uploadAndResizeImage($layer, $imageId, $imageType, 'thumbnail');
    }

    private function _uploadAndResizeImage($layer, $imageId, $imageType, $pictureSize)
    {
        $layer->resizeInPixel(
            $this->configParams[$pictureSize . 'Width'],
            $this->configParams[$pictureSize . 'Height'],
            1 // conserveProportion
        );

        $dirPath = $this->_calculateImagePath($imageType, $pictureSize);
        $fileName = $imageId . '.jpg';

        $layer->save(
            $dirPath,
            $fileName,
            0, //createFolders
            null, //backgroundColor
            $this->configParams['imageQuality']
        );
    }

    /**
     * @param string $imageType This can be 'store' or 'discount'
     * @param string $pictureSize
     */
    private function _calculateImagePath($imageType, $pictureSize)
    {
        if (!in_array($imageType, array('store', 'discount'))) {
            throw new Zend_Application_Exception('An uploaded image must whether discount or store');
        }

        $path = Application::getCarouselPicturesPath(false) . '/' . $imageType . '/';

        if ($pictureSize == 'thumbnail'){
            $path .= 'thumbs/';
        }

        return $path;
    }
}